package cn.com.xj.plat.controller;

import cn.com.xj.common.enums.AuditStatus;
import cn.com.xj.common.enums.YesOrNo;
import cn.com.xj.common.param.out.ServiceResp;
import cn.com.xj.common.param.valid.ValidUtils;
import cn.com.xj.common.service.aspect.bean.BeanUtil;
import cn.com.xj.plat.evt.*;
import cn.com.xj.plat.evt.bank.QueryBankEvt;
import cn.com.xj.plat.evt.carLength.QueryCarLengthEvt;
import cn.com.xj.plat.evt.common.BatchStatusByIdEvt;
import cn.com.xj.plat.evt.outInt.VerifyIdentity;
import cn.com.xj.plat.evt.userBank.AddUserBankEvt;
import cn.com.xj.plat.factory.BaseFactory;
import cn.com.xj.plat.service.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/plat/webUser")
public class WebUserController extends BaseController {

    @Autowired
    private CarLengthService carLengthService;
    @Autowired
    private WebUserService webUserService;
    @Autowired
    private DictService dictService;
    @Autowired
    private BankService bankService;
    @Autowired
    private UserBankService userBankService;
    @Autowired
    private OutIntService outIntService;

    @Value("${plat.comon.default-pwd:}")
    private String defaultPassword;


    @RequestMapping("/list")
    public String list(){
        return "/webUser/list";
    }

    @RequestMapping("/toAdd")
    public String toAdd(Model model){
        model.addAttribute("defaultPassword",defaultPassword);
        return "/webUser/edit";
    }

    @RequestMapping("/toBank")
    public String toBank(QueryWebUserEvt evt,Model model){

        if(evt.getId()==null)return "/common/error";
        ServiceResp userResp =
                webUserService.query(BeanUtil.transBean2Map(evt));
        if(userResp==null||!userResp.success())return "/common/error";
        List<Map<String,Object>> items = (List<Map<String,Object>>)userResp.getBody();
        model.addAttribute("user",items.get(0));
        // 查询合作银行列表
        QueryBankEvt queryBankEvt = new QueryBankEvt();
        ServiceResp<Object> resp =
                bankService.query(BeanUtil.transBean2Map(queryBankEvt));
        if(resp.success()){
            model.addAttribute("banks",resp.getBody());
        }
        model.addAttribute("userId",evt.getId());
        return "/webUser/bank";
    }

    @RequestMapping(value = "doAddBank",method = RequestMethod.POST)
    @ResponseBody
    public ServiceResp doAddBank(AddUserBankEvt evt, HttpSession session){
        try {
            return BaseFactory.getInstance().add(userBankService,evt,session);
        }catch (Exception e){
            e.printStackTrace();
            return new ServiceResp().error("系统错误");
        }
    }

    @RequestMapping(value = "doAdd",method = RequestMethod.POST)
    @ResponseBody
    public ServiceResp doAdd(AddWebUserEvt evt, HttpSession session){
        try {
            if(evt.getUserGroupId()!=null){
                evt.setUserGroupId(evt.getUserGroupId()==-4L?null:evt.getUserGroupId());
            }
            evt.setLoginPwd(defaultPassword);
            return BaseFactory.getInstance().add(webUserService,evt,session);
        }catch (Exception e){
            e.printStackTrace();
            return new ServiceResp().error("系统错误");
        }
    }

    @RequestMapping("/page")
    public String page(QueryWebUserEvt evt,Model model){
        try{
            BaseFactory.getInstance().page(webUserService,evt,model);
        }catch(Exception e){
            e.printStackTrace();
            return "/common/error";
        }
        return "/webUser/page";
    }

    @RequestMapping("/chooseList")
    public String chooseList(){
        return "/webUser/chooseList";
    }

    @RequestMapping("/chooseDriverList")
    public String chooseDriverList(QueryWebUserCarEvt evt,Model model){
        ServiceResp<Object> resp = carLengthService.
                query(BeanUtil.transBean2Map(new QueryCarLengthEvt()));
        model.addAttribute("carLengths", resp.getBody());
        model.addAttribute("evt",evt);
        return "/webUser/chooseDriverList";
    }

    @RequestMapping("/chooseDriverPage")
    public String chooseDriverPage(QueryWebUserCarEvt evt,Model model){
        try{
            if(evt.getInit()==1){
                ServiceResp<Object> resp = webUserService.queryUserWithCarCount(evt);
                model.addAttribute("total",resp.getBody());
            }
            ServiceResp<Object> respList = webUserService.queryUserWithCar(evt);
            model.addAttribute("list",respList.getBody());
        }catch(Exception e){
            e.printStackTrace();
            return "/common/error";
        }
        return "/webUser/chooseDriverPage";
    }

    @RequestMapping("/choosePage")
    public String choosePage(QueryWebUserEvt evt,Model model){
        try{
            evt.setCarownerStatus("DSQ");
            evt.setAuthStatus("SHTG");
            BaseFactory.getInstance().page(webUserService,evt,model);
        }catch(Exception e){
            e.printStackTrace();
            return "/common/error";
        }
        return "/webUser/choosePage";
    }

    /***进入菜单、按钮编辑页面*/
    @RequestMapping("/toEdit")
    public String toEdit(QueryWebUserEvt evt,Model model){
        try{
            if(evt.getId()==null){
                return "/common/error";
            }
            BaseFactory.getInstance().toEdit(webUserService,BeanUtil.transBean2Map(evt),model);
        }catch(Exception e){
            e.printStackTrace();
            return "/common/error";
        }
        return "/webUser/edit";
    }

    @RequestMapping("/toDetail")
     public String toDetail(QueryWebUserEvt queryWebUserEvt,Model model){
         try {
             queryWebUserEvt.setLoadBankCard(YesOrNo.Y.name());
             queryWebUserEvt.setLoadCar(YesOrNo.Y.name());
             queryWebUserEvt.setLoadUserInvoice(YesOrNo.Y.name());
             BaseFactory.getInstance().toDetail(
                     webUserService,BeanUtil.transBean2Map(queryWebUserEvt),model);
         } catch (Exception e) {
             e.printStackTrace();
             return "/common/error";
         }
         return "/webUser/detail";
     }

    @RequestMapping(value = "doEdit",method = RequestMethod.POST)
    @ResponseBody
    public ServiceResp doEdit(EditWebUserEvt evt){
        try {
            return BaseFactory.getInstance().doEdit(webUserService,evt);
        }catch (Exception e){
            e.printStackTrace();
            return new ServiceResp().error("系统错误");
        }
    }


    // 跳转到用户审核
    @RequestMapping(value = "toAudit",method = RequestMethod.GET)
    public String toAudit(QueryWebUserEvt evt,Model model){
        try {
            if(evt.getId()==null){
                return "/common/error";
            }
            QueryDictEvt queryDictEvt = new QueryDictEvt();
            queryDictEvt.setTableName("t_web_user");
            queryDictEvt.setColumnName("auditRemark");
            ServiceResp<Object> auditRemarks = dictService.queryCache(BeanUtil.transBean2Map(queryDictEvt));
            if (auditRemarks.success()) {
                model.addAttribute("auditRemarks", auditRemarks.getBody());
            }
            BaseFactory.getInstance().toDetail(webUserService,BeanUtil.transBean2Map(evt),model);
            return "/webUser/audit";
        }catch (Exception e){
            e.printStackTrace();
            return "";
        }
    }


    @RequestMapping(value = "audit",method = RequestMethod.POST)
    @ResponseBody
    public ServiceResp audit(AuditWebUserEvt evt){
        try {
            ServiceResp validResp = BaseFactory.getInstance().valid(evt);
            if(!validResp.success()) {
                return validResp.error(validResp.getHead().getRespMsg());
            }
            // 如果审核通过，先调用接口验证
//            if(AuditStatus.SHTG.name().equals(evt.getAuditStatus())){
//                // 查询用户信息是否存在
//                QueryWebUserEvt queryWebUserEvt = new QueryWebUserEvt();
//                queryWebUserEvt.setId(evt.getWebUserId());
//                ServiceResp<Object> resp =
//                        webUserService.query(BeanUtil.transBean2Map(queryWebUserEvt));
//                List<Map<String,Object>> items = (List<Map<String,Object>>)resp.getBody();
//                Map<String,Object> item = items.size()>0?items.get(0):null;
//                if(item==null)return new ServiceResp().error("用户信息不存在,无法执行审核操作");
//                VerifyIdentity verifyIdentity = new VerifyIdentity();
//                verifyIdentity.setiDCardNo(item.get("userCardNo").toString());
//                verifyIdentity.setMobilePhone(item.get("userPhone").toString());
//                verifyIdentity.setPersonName(item.get("userAlias").toString());
//                ServiceResp<Object> serviceResp =
//                        outIntService.verifyIdentity(verifyIdentity);
//                if(serviceResp!=null&&serviceResp.success()){
//                    String rs = serviceResp.getBody().toString();
//                    JSONObject object = JSON.parseObject(rs);
//                }
//            }
            return webUserService.auditUserAuth(BeanUtil.transBean2Map(evt));
        }catch (Exception e){
            e.printStackTrace();
            return new ServiceResp().error("系统错误");
        }
    }

    @RequestMapping(value = "doChangeStatus",method = RequestMethod.POST)
    @ResponseBody
    public ServiceResp doChangeStatus(BatchStatusByIdEvt evt){
        try {
            ServiceResp validResp = new ValidUtils().validate(evt);
            if(!validResp.success()) {
                return validResp.error(validResp.getHead().getRespMsg());
            }
            return webUserService.batchEditStatus(BeanUtil.transBean2Map(evt));
        }catch (Exception e){
            e.printStackTrace();
            return new ServiceResp().error("系统错误");
        }
    }

}
